package com.competition.login.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.competition.commonutils.JwtUtils;
import com.competition.commonutils.R;
import com.competition.login.entity.User;
import com.competition.login.entity.vo.FindPasswordVo;
import com.competition.login.entity.vo.RegisterVo;
import com.competition.login.service.UserService;
import com.competition.servicebase.exceptionhandler.MyException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 * 会员表 前端控制器
 * </p>
 *
 * @author testjava
 * @since 2021-02-19
 */
@RestController
@RequestMapping("/login/user")
@CrossOrigin
@Api(description ="用户登录与注册")
public class LoginController {

    @Autowired
    private UserService userService;
    //登录
    @PostMapping("login")
    @ApiOperation("接收用户输入信息(邮箱和密码)，返回token字符串")
    public R loginUser(@RequestBody User user){
        R loginInfo = userService.login(user);
        return loginInfo;
    }

    //注册
    @PostMapping("register")
    @ApiOperation("用户注册接口，输入邮箱，昵称，密码和验证码")
    public R registerUser(@RequestBody RegisterVo registerVo){
        R register = userService.register(registerVo);
        return register;
    }

    //根据token获取用户信息
    @GetMapping("info")
    @ApiOperation("登录成功后调用这个接口获取用户数据")
    public R getUserInfo(HttpServletRequest request){
        String memberId= JwtUtils.getMemberIdByJwtToken(request);
        User user = userService.getById(memberId);
        return R.ok().data("userInfo", user);
    }

    @PostMapping("updatePassword")
    @ApiOperation("找回密码需要传递用户邮箱与新密码")
    public R updatePassword(@RequestBody FindPasswordVo findPasswordVo, HttpServletRequest request){
        System.out.println(findPasswordVo);
        String code = findPasswordVo.getCode();
        String password = findPasswordVo.getPassword();
        QueryWrapper<User> userQueryWrapper=new QueryWrapper<>();
        userQueryWrapper.eq("email",findPasswordVo.getEmail());
        List<User> users = userService.list(userQueryWrapper);
        if(users.size()==1){
            User user = users.get(0);
            user.setPassword(password);
            userService.updateById(user);
        }else {
            return R.error().data("msg","该账号不存在");
        }
        return R.ok();
    }

    @PostMapping("test2")
    public void test2(HttpServletRequest request){
        Object attribute = request.getSession().getAttribute("666");
        System.out.println(attribute);
    }




}

